import hbDialog from "./hb-dialog.vue";
import { getLocation } from "@/common/http/location.js";

export default {
  props: {},
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var disx = e.pageX - el.offsetLeft;
        var disy = e.pageY - el.offsetTop;
        document.onmousemove = function (e) {
          el.style.left = e.pageX - disx + "px";
          el.style.top = e.pageY - disy + "px";
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
        };
      };
    },
  },
  data() {
    return {
      // 可注释
      textObj: {
        visible: false, // 控制弹框
        title: "", // 标题
        text: "", // 内容
        data: {}, // 要删除的内容
        center: "", // 是否居中显示
      },

      requireinfo: {
        lng: "",
        lat: "",
        radius: "",
      },
      //地图相关
      map: null,
      mapDocLayer: null, //全国景区点要素图层.mapx 点要素聚合图
      tk: "fb3eec44ed909be3536962ff90220975", // 天地图密钥 fb3eec44ed909be3536962ff90220975 2329c6061242b26cba5d2d9b4da9a776
      TiandiMap_vec: null,
      TiandiMap_vectcia: null,
      beginExtent: null, //存放初始化时地图窗口的范围，用于复位

      dvKey: 0, // dv自适应
      resultBoxShow: false, //查询结果盒子是否显示
      resultTableShow: false, //条件查询结果表格是否显示
      resultData: [], //条件查询结果数据
      tableTotal: 0, //结果总数
      tableEmptyText: "", //没有数据时显示
      tableCurrentPage: 1, //条件查询表格当前页
      tablePageSize: 20, //每页展示条数

      pointObj: null,
      geomObj: null,

      resultSource: null,
      resultLayer: null, //高亮显示查询结果的图

      boundingSource: null, //边界显示vector
      boundingLayer: null, //边界显示图层
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    /*
     * 初始化
     */
    init() {
      this.initMapCon();
      this.initTDBaseMap();
      this.initControl();
      this.initResultLayer();
      this.getPlace();
      this.initLocateLayer();
    },

    //获取当前位置
    getPlace() {
      getLocation()
        .then((location) => {
          this.requireinfo.lng = location.longitude.toFixed(6);
          this.requireinfo.lat = location.latitude.toFixed(6);
        })
        .catch((error) => {
          this.$message("获取当前位置失败，请手动输入经纬度坐标！");
        });
    },

    //初始化 地图容器
    initMapCon() {
      this.map = new ol.Map({
        target: "mapCon",
        view: new ol.View({
          projection: ol.proj.get("EPSG:3857"), //默认为 3857
          center: ol.proj.fromLonLat([104.912777, 34.730746]),
          minZoom: 1,
          zoom: 5,
        }),
      });
      // 地图窗口的初始范围
      this.beginExtent = this.map.getView().calculateExtent(this.map.getSize());
    },
    //初始化 天地图底图
    initTDBaseMap() {
      let layerOrigin_vec = new ol.layer.Tile({
        name: "天地图矢量图层",
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          crossOrigin: "Anonymous",
          wrapX: false,
        }),
      });
      let layerOrigin_vectcia = new ol.layer.Tile({
        name: "天地图矢量注记图层",
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          crossOrigin: "Anonymous",
          wrapX: false,
        }),
      });
      //定义颜色转换方法
      let reverseFunc = function (pixelsTemp) {
        //蓝色
        for (var i = 0; i < pixelsTemp.length; i += 4) {
          var r = pixelsTemp[i];
          var g = pixelsTemp[i + 1];
          var b = pixelsTemp[i + 2];
          //运用图像学公式，设置灰度值
          var grey = parseInt((r + g + b) / 3);
          //将rgb的值替换为灰度值
          pixelsTemp[i] = grey;
          pixelsTemp[i + 1] = grey;
          pixelsTemp[i + 2] = grey;

          //基于灰色，设置为任意颜色 34, 52, 88
          var targetR = 34;
          var targetG = 52;
          var targetB = 88;
          var baseGrey = 242; //202
          pixelsTemp[i] = targetR + baseGrey - pixelsTemp[i];
          pixelsTemp[i + 1] = targetG + baseGrey - pixelsTemp[i + 1];
          pixelsTemp[i + 2] = targetB + baseGrey - pixelsTemp[i + 2];
        }
      };
      //openlayer 像素转换类，可以直接当做source使用
      const raster_vec = new ol.source.Raster({
        sources: [
          //传入图层，这里是天地图矢量图或者天地图矢量注记
          layerOrigin_vec,
        ],
        //这里设置为image类型，与官方示例不同，优化速度
        operationType: "image",
        operation: function (pixels, data) {
          //执行颜色转换方法，注意，这里的方法需要使用lib引入进来才可以使用
          reverseFunc(pixels[0].data);
          return pixels[0];
        },
        //线程数量
        threads: 10,
        //允许operation使用外部方法
        lib: {
          reverseFunc: reverseFunc,
        },
      });
      const raster_vectcia = new ol.source.Raster({
        sources: [
          //传入图层，这里是天地图矢量图或者天地图矢量注记
          layerOrigin_vectcia,
        ],
        //这里设置为image类型，与官方示例不同，优化速度
        operationType: "image",
        operation: function (pixels, data) {
          //执行颜色转换方法，注意，这里的方法需要使用lib引入进来才可以使用
          reverseFunc(pixels[0].data);
          return pixels[0];
        },
        //线程数量
        threads: 10,
        //允许operation使用外部方法
        lib: {
          reverseFunc: reverseFunc,
        },
      });
      //创建新图层，注意，必须使用 ImageLayer
      this.TiandiMap_vec = new ol.layer.Image({
        name: "天地图矢量图层",
        source: raster_vec,
      });
      this.TiandiMap_vectcia = new ol.layer.Image({
        name: "天地图矢量注记图层",
        source: raster_vectcia,
      });
      // 设置图层透明度
      this.TiandiMap_vec.setOpacity(0.6);
      //this.TiandiMap_vectcia.setOpacity(0.6)
      //添加图层
      this.map.addLayer(this.TiandiMap_vec);
      this.map.addLayer(this.TiandiMap_vectcia);
    },
    //初始化 地图控件
    initControl() {
      // 鼠标位置
      let mousePositionControl = new ol.control.MousePosition({
        //坐标格式
        coordinateFormat: ol.coordinate.createStringXY(4),
        //地图投影坐标系（若未设置则输出为默认投影坐标系下的坐标）
        projection: "EPSG:4326",
        //坐标信息显示样式类名，默认是'ol-mouse-position'
        className: "custom-mouse-position",
        //显示鼠标位置信息的目标容器
        target: document.getElementById("mouse-position"),
        //未定义坐标的标记
        undefinedHTML: "&nbsp;",
      });
      this.map.addControl(mousePositionControl);
      //实例化ZoomSlider控件并加载到地图容器中
      let zoomslider = new ol.control.ZoomSlider();
      this.map.addControl(zoomslider);
      //缩放至范围,复位
      let zoomToExtent = new ol.control.ZoomToExtent({
        extent: this.beginExtent,
      });
      this.map.addControl(zoomToExtent);
    },
    //初始化 查询结果高亮显示图层
    initResultLayer() {
      this.resultSource = new ol.source.Vector({ wrapX: false });
      this.resultLayer = new ol.layer.Vector({
        name: "查询结果显示图层",
        source: this.resultSource,
        //原版style
        // style: new ol.style.Style({
        //   image: new ol.style.Icon({
        //     src: require("@/assets/粒子光晕.png"),
        //     scale: 0.3,
        //   }),
        // }),
        //根据要素类型区分style
        style: function (feature, resolution) {
          var type = feature.getGeometry().getType(); //获取各个个体编号
          var style = null;
          if (type === "Circle") {
            style = new ol.style.Style({
              //填充色
              fill: new ol.style.Fill({
                color: "rgb(255, 0, 0)",
              }),
              //边线颜色
              stroke: new ol.style.Stroke({
                color: "red",
                width: 2,
              }),
            });
          } else {
            style = new ol.style.Style({
              image: new ol.style.Icon({
                src: require("../point.png"),
                scale: 0.3,
              }),
            });
          }
          return [style];
        },
      });
      this.map.addLayer(this.resultLayer);

      //实例化一个矢量图层Vector作为绘制层
      this.boundingSource = new ol.source.Vector({
        features: [],
        //是否在地图水平坐标轴上重复
        wrapX: false,
      });
      this.boundingLayer = new ol.layer.Vector({
        source: this.boundingSource,
        style: new ol.style.Style({
          //填充色
          fill: new ol.style.Fill({
            // color: 'rgba(0,0,255,0.2)'
            color: "rgba(52,83,223,0.2)",
          }),
          //边线样式
          stroke: new ol.style.Stroke({
            color: "blue",
            width: 2,
          }),
        }),
      });
      //将绘制层添加到地图容器中
      this.map.addLayer(this.boundingLayer);
    },
    //初始化 定位图层
    initLocateLayer() {
      this.locateSource = new ol.source.Vector({ wrapX: false });
      this.locateLayer = new ol.layer.Vector({
        source: this.locateSource,
        
      });
      this.map.addLayer(this.locateLayer);
    },
    /*
     * 地图文档查询方法
     */
    docFeatureQuery() {
      const radius = document.getElementById("radius").value;
      let pos = [document.getElementById("lng").value, document.getElementById("lat").value];
      let c = ol.proj.transform([parseFloat(pos[0]), parseFloat(pos[1])], "EPSG:4326", "EPSG:3857");

      let pointObj = new Zondy.Object.Point2D(c[0], c[1]);
      this.geomObj = new Zondy.Object.Circle(pointObj, radius);

      //初始化查询结构对象，设置查询结构包含几何信息
      const queryStruct = new Zondy.Service.QueryFeatureStruct();
      //是否包含几何图形信息
      queryStruct.IncludeGeometry = true;
      //是否包含属性信息
      queryStruct.IncludeAttribute = true;
      //是否包含图形显示参数
      queryStruct.IncludeWebGraphic = false;
      //实例化查询参数对象
      var queryParam = new Zondy.Service.QueryByLayerParameter("gdbp://MapGisLocal/itravel/sfcls/全国餐饮", {
        resultFormat: "json",
        struct: queryStruct,
      });
      const rule = new Zondy.Service.QueryFeatureRule({
        //是否将要素的可见性计算在内
        EnableDisplayCondition: false,
        //是否完全包含
        MustInside: false,
        //是否仅比较要素的外包矩形
        CompareRectOnly: false,
        //是否相交
        Intersect: true,
      });
      queryParam.rule = rule;
      queryParam.geometry = this.geomObj;
      //设置查询分页号
      queryParam.pageIndex = this.tableCurrentPage - 1;
      //设置每页记录数
      queryParam.recordNumber = this.tablePageSize;
      //实例化图层查询服务对象
      var queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
        ip: window.server.GIS_IP,
        port: window.server.GIS_PORT,
      });
      queryService.query(this.docQuerySuccess, this.docQueryError);
    },
    //地图文档查询 - 成功回调
    docQuerySuccess(result) {
      if (result.TotalCount == 0) {
        this.tableEmptyText = "暂无数据";
        return;
      }
      //初始化Zondy.Format.PolygonJSON类
      let format = new Zondy.Format.PolygonJSON();
      //将MapGIS要素JSON反序列化为ol.Feature类型数组
      let features = format.read(result);
      this.afterQuery(result, features);
    },
    //地图文档查询 - 失败回调
    docQueryError(e) {
      this.tableEmptyText = "暂无数据";
    },
    //查询前重置数据
    beforeQuery() {
      this.tableEmptyText = "正在查询中...";
      //显示查询结果盒子
      this.resultBoxShow = true;
      this.resultTableShow = true;
      this.$nextTick(() => {
        this.dvKey++;
      });
      //重置数据
      this.resultData = [];
      this.tableTotal = 0;
      this.tableCurrentPage = 1;
      this.removeMapResult();
      this.tablePageSize = 5;
      this.locateSource.clear();
    },
    //查询后处理数据
    afterQuery(result, features) {
      //表格显示结果
      this.refreshTableResult(result, features);
      //地图显示结果
      this.refreshMapResult(features);
    },

    /*
     * 查询结果-表格显示
     */
    //表格显示查询结果
    refreshTableResult(result, features) {
      //数据
      this.resultData = [];
      for (let i = 0; i < features.length; i++) {
        this.resultData.push(features[i].getProperties().values_);
      }
      //总数
      this.tableTotal == 0 ? (this.tableTotal = result.TotalCount) : null;
    },
    //清空表格查询结果
    removeTableResult() {
      //关闭结果表格盒子
      this.resultBoxShow = false;
      this.resultTableShow = false;
      this.resultData = [];
      this.tableTotal == 0;
      this.requireinfo.lng = "";
      this.requireinfo.lat = "";
      this.requireinfo.radius = "";
    },
    //结果表格 - 每页展示条数改变，重新获取第0页数据
    tableSizeChange() {
      this.tableCurrentPage = 1;
      this.docFeatureQuery();
    },
    //结果表格 - 当前页改变，获取新当前页数据
    tableCurrentChange() {
      this.docFeatureQuery();
    },
    //关闭查询结果盒子按钮
    resultBoxClose() {
      //关闭查询结果盒子
      this.resultBoxShow = false;
      this.resultTableShow = false;
    },
    //收起、展开结果表格按钮，dv边框自适应
    resultTableChange() {
      this.resultTableShow = !this.resultTableShow;
      this.$nextTick(() => {
        this.dvKey++;
      });
    },

    /*
     *  查询结果-地图显示
     */
    //更新地图显示的查询结果
    //需要修改成现实萤火图待写
    refreshMapResult(features) {
      const radius = document.getElementById("radius").value;
      let pos = [document.getElementById("lng").value, document.getElementById("lat").value];
      var circle = new ol.geom.Circle(ol.proj.transform([parseFloat(pos[0]), parseFloat(pos[1])], "EPSG:4326", "EPSG:3857"), parseFloat(radius));
      //将圆几何添加到地图进行显示（非必需，仅仅为了在地图上高亮显示图形）
      var boundingCircle = new ol.Feature({
        geometry: circle,
      });
      this.boundingSource.clear();
      this.boundingSource.addFeatures([boundingCircle]);

      //修改zoom尺度
      this.resultSource.clear();
      this.resultSource.addFeatures(features);
      const extent = this.resultSource.getExtent();

      this.map.getView().fit(extent);
      this.map.getView().setZoom(this.map.getView().getZoom());
    },
    //清空边界显示
    removeBounding() {
      this.boundingSource.clear();
    },
    //清空地图显示的查询结果
    removeMapResult() {
      //清空显示内容
      this.boundingSource.clear();
      this.resultSource.clear();
    },
    //复位全国景区点要素图层
    refreshSceneryLayer() {
      //复位
      let r = this.map.getView().getResolutionForExtent(this.beginExtent, this.map.getSize());
      this.map.getView().setResolution(r);
      this.map.getView().setCenter(ol.extent.getCenter(this.beginExtent));
    },
    //查询按钮被点击
    dataQueryBtn() {
      this.beforeQuery();
      this.docFeatureQuery();
    },
    //重置按钮被点击
    dataResetBtn() {
      //清空表格显示结果
      this.removeTableResult();
      //移除地图显示结果
      this.removeMapResult();
      this.refreshSceneryLayer();
      this.removeBounding(); //重置时删除边界
      this.getPlace();
      this.locateSource.clear();
    },
    del_content() {
      this.textObj.visible = true;
      // this.textObj.title = '删除';
      this.textObj.text = "你确定要删除吗？";
    },
    del_text(val) {
      // 删除再次确认按钮提示
      this.textObj.visible = false;
      this.$message.success("删除成功");
    },
    handleClick(row){
      this.locateSource.clear();
      // console.log(row.name)
      // console.log(row.latitude)
      // console.log(row.longitude)
      let pos = [parseFloat(row.latitude), parseFloat(row.longitude)];//4326坐标
      pos = ol.proj.transform([pos[1],pos[0]], 'EPSG:4326', 'EPSG:3857');//3857坐标
      // console.log(pos)

      let feature = new  ol.Feature({
        geometry:  new ol.geom.Point(pos)
      });
      let style = new ol.style.Style({
        image: new ol.style.Icon({
          src: require("@/assets/餐厅.png"),
          scale: 0.3,
        }),
        text: new ol.style.Text({
          font: 'normal 18px 黑体',
          textAlign: 'center',
          // 基准线
          textBaseline: 'middle',
          offsetY: -45,
          offsetX: 0,
          // backgroundFill: new ol.style.Stroke({
          //     color: 'rgba(0,0,255,0.7)',
          // }),
          // 文本填充样式
          fill: new ol.style.Fill({
              color: 'rgba(236,218,20,1)'
          }),
          padding: [5, 5, 5, 5],
          text: row.name,
      })
      })
      
      feature.setStyle(style);
      this.locateSource.addFeatures([feature])
    },
  },
  components: {
    hbDialog,
  },
};
